class Component {
    setState(state) {
        let oldEl = this.el
        this.state = state
        this._renderDOM()
        if (this.onStateChange) {
            this.onStateChange(oldEl, this.el)
        }
    }

    _renderDOM() {
        this.el = createDOMFromString(this.render())
        if (this.onClick) {
            this.el.addEventListener('click', this.onClick.bind(this), false)
        }
        return this.el
    }
}

class LikeButton extends Component {
    constructor(props = {}) {
        super(props)
        this.props = props
        this.state = { isLiked: false }
    }

    onClick() {
        this.setState({
            isLiked: !this.state.isLiked
        })
    }

    render() {
        return `<button class='like-btn'>
          <span class='like-text'>${this.state.isLiked ? 'cancel' : 'ok'}</span>
          <span >up</span>
        </button>`
    }
}

function createDOMFromString(string = '') {
    let newDiv = document.createElement("div")
    newDiv.insertAdjacentHTML('afterbegin', string)
    return newDiv
}

mount = function (component, wrapper) {
    wrapper.appendChild(component._renderDOM())
    component.onStateChange = (oldEl, newEl) => {
        wrapper.insertBefore(newEl, oldEl)
        wrapper.removeChild(oldEl)
    }
}

let wrapper = document.getElementById('app')
mount(new LikeButton(), wrapper)
